import { ref } from 'vue';
import type { AnyObj, FN } from '@types/global';

export function useGetDataPaging(options : { api : FN; params ?: AnyObj | FN; handlerData ?: (list : AnyObj[]) => AnyObj[]; }) {
	const list = ref<AnyObj[]>([]);
	const end = ref(false);
	let pageNum = 0;
	const pageSize = 10;
	let index = 0;

	function loadData(argIndex : number) {
		pageNum++;
		const params : Record<string, any> = {
			pageNum,
			pageSize,
		};

		if (options.params) {
			if (options.params instanceof Function) {
				Object.assign(params, options.params());
			} else {
				Object.assign(params, { ...(options.params ?? {}) })
			}
		}

		options.api(params).then((result : AnyObj) => {
			if (index != argIndex) {
				return;
			}
			if (options.handlerData) {
				options.handlerData(result.rows);
			}
			end.value = pageNum * pageSize >= result.total;
			list.value.push(...result.rows);
		});
	}


	function refresh() {
		index++;
		list.value = [];
		end.value = false;
		pageNum = 0;
		loadData(index);
	}

	function tolower() {
		if (end.value) return;
		index++;
		loadData(index);
	}

	return {
		list,
		end,
		refresh,
		tolower
	}
}